<template>
  <div>
    <van-field v-model="resultLabel" v-bind="$attrs">
      <template #input>
        <treeselect
          v-model="resultValue"
          :multiple="multiple"
          :options="columns"
          :normalizer="normalizer"
          @select="change"
        />
      </template>
    </van-field>
  </div>
</template>

<script>
// import the component
import Treeselect from "@riophae/vue-treeselect";
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "VanFieldVueTreeSelect",
  // register the component
  components: { Treeselect },
  model: {
    prop: "selectValue"
  },
  props: {
    columns: {
      type: Array,
      default: function() {
        return [];
      }
    },
    selectValue: {
      type: [Array, String],
      default: function() {
        return [];
      }
    },
    option: {
      type: Object,
      default: function() {
        return { label: "label", value: "value" };
      }
    },
    multiple: {
      type: Boolean,
      default: function() {
        return false;
      }
    }
  },
  computed: {
    resultLabel: {
      get() {
        if (!this.resultValue) return "";
        const res = this.columns.filter(item => {
          return this.resultValue.indexOf(item[this.option.value]) > -1;
        });
        const resLabel = res.map(item => {
          return item[this.option.label];
        });
        return resLabel.join(",");
      },
      set() {}
    }
  },
  data() {
    return {
      resultValue: JSON.parse(JSON.stringify(this.selectValue)) || []
    };
  },
  methods: {
    change(val) {
      //当数据改变
      this.$emit("change", val, this.resultValue);
    },
    normalizer(node) {
      if (node.children == null || node.children == "null") {
        delete node.children;
      }
      return {
        id: node[this.option.value],
        label: node[this.option.label]
      };
    }
  },
  watch: {
    selectValue: function(newVal) {
      this.resultValue = newVal;
    },
    resultValue(val) {
      this.$emit("input", val);
    }
  }
};
</script>

<style lang="less">
.van-cell {
  overflow: visible;
  .vue-treeselect__control {
    border: 0;
  }
  .vue-treeselect__menu {
    border-radius: 0;
  }
}
</style>
